package com.sita.bluetactivity.TripFragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.DateUtils;
import com.sita.bluetactivity.Base.FormatUtils;
import com.sita.bluetactivity.Base.NumberUtils;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.R;
import com.sita.bluetactivity.http.RestClient;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Jason on 2016/10/8.
 */

public class DayDataFragment extends Fragment{
    LineChartView mileageChart;
    LineChartView speedChart;
    LineChartView powerChart;
    LineChartView allTimeChart;
  //  LineChartView mitigationChart;
    private float mTotalMileage = 2.4f;
    private long mTotalTime = 11; // unit is minute
    private float mTotalBatteryCost = 40; // ah
    private float mAverageSpeed = 24; // km.h
    private int mGreenCost = 0; // %
    //存放x轴的坐标
    ArrayList<String> xAxisDate = new ArrayList<>();
    private View rootView;//缓存Fragment
    private List<PointValue> mMileagePointValues = new ArrayList<>();
    private List<AxisValue> mMileageAxisValues = new ArrayList<>();

    private List<PointValue> mSpeedPointValues = new ArrayList<>();
    private List<AxisValue> mSpeedAxisValues = new ArrayList<>();

    private List<PointValue> mPowerPointValues = new ArrayList<>();
    private List<AxisValue> mPowerAxisValues = new ArrayList<>();

    private List<PointValue> mAllMilePointValues = new ArrayList<>();
    private List<AxisValue> mAllMileAxisValues = new ArrayList<>();

    private List<PointValue> mMitigationPointValues = new ArrayList<>();
    private List<AxisValue> mMitigationAxisValues = new ArrayList<>();

    private TextView dateView,mileageView,timeHourView,timeMinuteView,
            powerView,avSpeedView,costView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trip_day, null);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getTxView();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        dateView.setText(DateUtils.formatDayOfWeek(calendar.getTimeInMillis()));

        resetTopTable();
        fetchData();
    }
    private void getTxView(){
        allTimeChart = (LineChartView) getActivity().findViewById(R.id.all_time_chat);

       // mitigationChart = (LineChartView) getActivity().findViewById(R.id.mitigation_chat);

        mileageChart = (LineChartView) getActivity().findViewById(R.id.mileage_chart);

        speedChart = (LineChartView) getActivity().findViewById(R.id.speed_chart);

        powerChart = (LineChartView) getActivity().findViewById(R.id.power_chart);

        dateView = (TextView) getActivity().findViewById(R.id.current_date);
        mileageView = (TextView) getActivity().findViewById(R.id.data_mileage);
        timeHourView = (TextView) getActivity().findViewById(R.id.data_time_hour);
       // timeMinuteView = (TextView) getActivity().findViewById(R.id.data_time_minute);
        powerView = (TextView) getActivity().findViewById(R.id.data_power);
        avSpeedView = (TextView) getActivity().findViewById(R.id.data_average_speed);
        costView = (TextView) getActivity().findViewById(R.id.data_cost);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        String x =DateUtils.formatDate(calendar.getTimeInMillis(), DateUtils.YYYYMM);
        dateView.setText(x);
    }

    private void fetchData() {
        DayMsgRequest request = new DayMsgRequest();
        request.controllerId = SpUtils.getString("AccountId",null,BaseApplication.getContext());

        RestClient.getRestService().dayMsg(request, new Callback<DayMesBackBean>() {
            @Override
            public void success(DayMesBackBean dayMesBackBean, Response response) {
                if (dayMesBackBean != null) {
                     mTotalBatteryCost = NumberUtils.setValue(dayMesBackBean.getData().getSoc_last_day10());
                     mTotalMileage = NumberUtils.setValue(dayMesBackBean.getData().getMileage_last_day10());
                      mTotalTime = dayMesBackBean.getData().getTimes_last_day10();
                      mAverageSpeed = FormatUtils.formatSpeed(NumberUtils.setValue(dayMesBackBean.getData().getSpeed_last_day10()));
                    // 总里程*0.7+(总里程²/总时长)*2=XXm³
                    mGreenCost = dayMesBackBean.getData().getRanking_last_day10();
                    setTopTable();
                    getDayValues();
                    initMileageChart(dayMesBackBean);
                    initSpeedChart(dayMesBackBean);
                    initPowerChart(dayMesBackBean);
                    initAllMileChart(dayMesBackBean);
                   // initMitigationChart(dayMesBackBean);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("ssss",error.toString());

            }
        });
    }

    private void resetTopTable() {
        setTopTableData(0f, 0, 0f, 0f, 0);
    }

    private void setTopTableData(float totalDistance, int minutes, float speed, float batteryCost, int greenCost) {
        mileageView.setText(String.valueOf(NumberUtils.formatNumber(totalDistance)));
        FormatUtils.TimeHourMinute time = FormatUtils.formatTimeHourMinute(minutes);
        timeHourView.setText(String.valueOf(time.hour));
       // timeMinuteView.setText(String.valueOf(time.minute));
        avSpeedView.setText(String.valueOf(NumberUtils.formatNumber(speed)));
        powerView.setText(String.valueOf(NumberUtils.formatNumber(batteryCost)));
        costView.setText("第"+greenCost+"名");
    }

    private void setTopTable() {
        setTopTableData(mTotalMileage / 1000f,
                (int) mTotalTime / 1000 / 60,
                mAverageSpeed,
                mTotalBatteryCost,
                mGreenCost);
    }

    //x轴标注相同，只需要计算一次就可以
    private void getDayValues() {
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        int lastDay = calendar.get(Calendar.DATE);//得到前一天
        int currentMonth = calendar.get(Calendar.MONTH) + 1;//当前月份
        int currentYear = calendar.get(Calendar.YEAR);//当前年份
        if (lastDay >= 10) {
            for (int i = lastDay - 9; i <= lastDay; i++) {
                xAxisDate.add(String.valueOf(i) + "日");
            }
        } else {
            //先计算上一个月一共有多少天
            Calendar time = Calendar.getInstance();
            time.clear();
            time.set(Calendar.YEAR, currentYear);
            time.set(Calendar.MONTH, currentMonth - 2);//注意,Calendar对象默认一月为0
            int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数

            for (int i = 10 - lastDay; i > 0; i--) {
                xAxisDate.add(String.valueOf(day - i + 1) + "日");
            }
            for (int i = 1; i <= lastDay; i++) {
                xAxisDate.add(String.valueOf(i) + "日");
            }
        }
    }

    private void initMileageChart(DayMesBackBean response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.getData().getMileage_last_day01() * 0.001f);
        yData.add(response.getData().getMileage_last_day02() * 0.001f);
        yData.add(response.getData().getMileage_last_day03() * 0.001f);
        yData.add(response.getData().getMileage_last_day04() * 0.001f);
        yData.add(response.getData().getMileage_last_day05() * 0.001f);
        yData.add(response.getData().getMileage_last_day06() * 0.001f);
        yData.add(response.getData().getMileage_last_day07() * 0.001f);
        yData.add(response.getData().getMileage_last_day08() * 0.001f);
        yData.add(response.getData().getMileage_last_day09() * 0.001f);
        yData.add(response.getData().getMileage_last_day10() * 0.001f);
        getAxisLables(xAxisDate, mMileageAxisValues);
        getAxisPoints(yData, mMileagePointValues);
        initLineChart(mMileagePointValues, mMileageAxisValues, mileageChart, Collections.max(yData));

    }

    private void initSpeedChart(DayMesBackBean response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.getData().getSpeed_last_day01()*1f);
        yData.add(response.getData().getSpeed_last_day02()*1f);
        yData.add(response.getData().getSpeed_last_day03()*1f);
        yData.add(response.getData().getSpeed_last_day04()*1f);
        yData.add(response.getData().getSpeed_last_day05()*1f);
        yData.add(response.getData().getSpeed_last_day06()*1f);
        yData.add(response.getData().getSpeed_last_day07()*1f);
        yData.add(response.getData().getSpeed_last_day08()*1f);
        yData.add(response.getData().getSpeed_last_day09()*1f);
        yData.add(response.getData().getSpeed_last_day10()*1f);
        getAxisLables(xAxisDate, mSpeedAxisValues);
        getAxisPoints(yData, mSpeedPointValues);
        initLineChart(mSpeedPointValues, mSpeedAxisValues, speedChart, Collections.max(yData));

    }

    private void initPowerChart(DayMesBackBean response) {
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.getData().getSoc_last_day01()*1f);
        yData.add(response.getData().getSoc_last_day02()*1f);
        yData.add(response.getData().getSoc_last_day03()*1f);
        yData.add(response.getData().getSoc_last_day04()*1f);
        yData.add(response.getData().getSoc_last_day05()*1f);
        yData.add(response.getData().getSoc_last_day06()*1f);
        yData.add(response.getData().getSoc_last_day07()*1f);
        yData.add(response.getData().getSoc_last_day08()*1f);
        yData.add(response.getData().getSoc_last_day09()*1f);
        yData.add(response.getData().getSoc_last_day10()*1f);
        getAxisLables(xAxisDate, mPowerAxisValues);
        getAxisPoints(yData, mPowerPointValues);
        initLineChart(mPowerPointValues, mPowerAxisValues, powerChart, Collections.max(yData));
    }
    private void initAllMileChart(DayMesBackBean response){
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.getData().getTimes_last_day01()*1f);
        yData.add(response.getData().getTimes_last_day02()*1f);
        yData.add(response.getData().getTimes_last_day03()*1f);
        yData.add(response.getData().getTimes_last_day04()*1f);
        yData.add(response.getData().getTimes_last_day05()*1f);
        yData.add(response.getData().getTimes_last_day06()*1f);
        yData.add(response.getData().getTimes_last_day07()*1f);
        yData.add(response.getData().getTimes_last_day08()*1f);
        yData.add(response.getData().getTimes_last_day09()*1f);
        yData.add(response.getData().getTimes_last_day10()*1f);
        getAxisLables(xAxisDate, mAllMileAxisValues);
        getAxisPoints(yData, mAllMilePointValues);
        initLineChart(mAllMilePointValues, mAllMileAxisValues, allTimeChart, Collections.max(yData));
    }
    private void initMitigationChart(DayMesBackBean response){
        ArrayList<Float> yData = new ArrayList<>();
        yData.add(response.getData().getSoc_last_day01()*1f);
        yData.add(response.getData().getSoc_last_day02()*1f);
        yData.add(response.getData().getSoc_last_day03()*1f);
        yData.add(response.getData().getSoc_last_day04()*1f);
        yData.add(response.getData().getSoc_last_day05()*1f);
        yData.add(response.getData().getSoc_last_day06()*1f);
        yData.add(response.getData().getSoc_last_day07()*1f);
        yData.add(response.getData().getSoc_last_day08()*1f);
        yData.add(response.getData().getSoc_last_day09()*1f);
        yData.add(response.getData().getSoc_last_day10()*1f);
        getAxisLables(xAxisDate, mMitigationAxisValues);
        getAxisPoints(yData, mMitigationPointValues);
      //  initLineChart(mMitigationPointValues, mMitigationAxisValues, mitigationChart, Collections.max(yData));
    }

    /**
     * 初始化LineChart的一些设置.
     */
    private void initLineChart(List<PointValue> mPointValues, List<AxisValue> mAxisValues, LineChartView mLineChartView, float mMaxValue) {
        mLineChartView.setVisibility(View.VISIBLE);
        Line line = new Line(mPointValues).setCubic(true);  //折线的颜色
        List<Line> lines = new ArrayList<>();
       // line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(false);//曲线是否平滑
        line.setFilled(true);//是否填充曲线的面积
        line.setColor(ContextCompat.getColor(BaseApplication.getContext(),R.color.white));
        line.setStrokeWidth(1);

        line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);
        axisX.setTextColor(Color.WHITE);  //设置字体颜色
        axisX.setTextSize(8);//设置字体大小
        axisX.setValues(mAxisValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasTiltedLabels(false);//x 轴字为水平
        Axis axisY = new Axis();  //Y轴
        axisY.setTextColor(Color.WHITE);  //设置字体颜色
        axisY.setTextSize(8);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        mLineChartView.setInteractive(true);
        mLineChartView.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);
        mLineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        mLineChartView.setLineChartData(data);
        mLineChartView.setVisibility(View.VISIBLE);

        final Viewport v = new Viewport(mLineChartView.getMaximumViewport());
        v.bottom = 0;
        v.top = mMaxValue + 10;
        v.left = 0;
        v.right = 9;
        mLineChartView.setMaximumViewport(v);
        mLineChartView.setCurrentViewport(v);

        // 设置缩放倍数,so important(15可以看成是x坐标对应为15(x总共40),0看成是y 坐标对应为0)
        mLineChartView.setZoomLevelWithAnimation((float) 20, (float) 0, (float) 1);
    }

    /**
     * X 轴的值
     */
    private void getAxisLables(ArrayList<String> values, List<AxisValue> mAxisValues) {
        for (int i = 0; i < values.size(); i++) {
            mAxisValues.add(new AxisValue(i).setLabel(values.get(i)));
        }
    }

    /**
     * 图表的每个点的值
     */
    private void getAxisPoints(ArrayList<Float> values, List<PointValue> mPointValues) {
        for (int i = 0; i < values.size(); i++) {
            mPointValues.add(new PointValue(i, values.get(i)));
        }
    }
}
